package main

import(
	"fmt"
	"net"
	"sync"
	"io"
	"time"
)

type Server struct{
	Ip        string
	Port      int

	OnlineMap map[string]*User
	mapLock   sync.RWMutex

	Message   chan string
}

func NewServer(ip string,port int) *Server {
	server := &Server{
		Ip:        ip,
		Port:      port,
		OnlineMap: make(map[string]*User),
		Message:   make(chan string),
	}
	return server
}

func (this *Server) ListenMessage (){
	for{
		msg := <- this.Message

		this.mapLock.Lock()
		for _,client := range this.OnlineMap{
			client.channel <- msg
		}
		this.mapLock.Unlock()
	}
}

func (this *Server) Broadcast(user *User, msg string){
	sendMsg := "[" + user.Addr + "]" + " " + user.Name + ":" + msg
	this.Message <- sendMsg
}

func (this *Server)Handle(conn net.Conn)  {
	user := NewUser(conn, this)
	fmt.Println("One new client connect SUCCESS!")
	user.Online()

	isLive := make(chan bool)

	go func ()  {
		buf := make([]byte, 4096)
		for{
			n,err := conn.Read(buf)
			if n == 0{
				user.Offline()
				return
			}
			if err != nil && err != io.EOF{
				fmt.Println("conn.Read error,error is ",err)
				return
			}

			msg := string(buf[0:n-1])
			user.DoMessage(msg)
			isLive <- true
		}
	}()

	select{
	case <- isLive:

	case <-time.After(time.Second * 3600):
		user.SendMessage("Long time on message, get out.")
		close(user.channel)
		conn.Close()
		return
	}
}

func (this *Server)Start()  {
	listener ,err := net.Listen("tcp",fmt.Sprintf("%s:%d",this.Ip,this.Port))
	if err != nil{
		fmt.Println("net.Listen error,error is ",err)
		return
	}
	fmt.Println("tcp connect SUCCESS! ")
	
	defer listener.Close()

	go this.ListenMessage()

	for{
		conn,err := listener.Accept()
		if err != nil{
			fmt.Println("Accept error,error is ",err)
			continue
		}

		go this.Handle(conn)
	}

}